/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.elysian.translator;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Properties;
import java.util.Set;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

/**
 *
 * @author ydubey
 */
public class Translator
{

    public static String translate(String arg) throws IOException
    {
        String submitURL = "http://babelfish.yahoo.com/translate_txt";
        Properties properties = new Properties();
        properties.put("trtext", arg);
        properties.put("lp", "en_fr");
        String response = new String(download(submitURL, properties));
        int index = response.indexOf("<div id=\"result\">");
        if (index != -1)
        {
            int start = index + "<div id=\"result\"><div style=\"padding:0.6em;\">".length();
            int end = response.indexOf("</div>", start);
            String translated = response.substring(start, end);
            return translated;
        }
        return null;
    }

    private static String createURL(String urlToDownload, Properties properties) throws UnsupportedEncodingException
    {
        StringBuilder stringBuilder = new StringBuilder(urlToDownload);
        Set keys = properties.keySet();
        String pre = "?";
        for (Object key : keys)
        {
            stringBuilder.append(pre);
            pre = "&";
            stringBuilder.append(URLEncoder.encode(key.toString(), "UTF-8"));
            stringBuilder.append("=");
            stringBuilder.append(URLEncoder.encode(properties.get(key).toString(), "UTF-8"));
        }
        return stringBuilder.toString();
    }

    private static byte[] download(String urlToDownload, Properties properties) throws IOException
    {
        String downloadURL = createURL(urlToDownload, properties);
        //System.out.println("Downloading " + downloadURL);
        // Create an instance of HttpClient.
        HttpClient client = new HttpClient();
        client.getHostConfiguration().setProxy("co.proxy.avaya.com", 8000);

        // Create a method instance.
        GetMethod method = new GetMethod(downloadURL);

        // Provide custom retry handler is necessary
        method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(3, false));
        byte[] responseBody = null;
        try
        {
            // Execute the method.
            int statusCode = client.executeMethod(method);

            if (statusCode != HttpStatus.SC_OK)
            {
                System.err.println("Method failed: " + method.getStatusLine());
            }

            // Read the response body.
            responseBody = method.getResponseBody();

        } catch (HttpException e)
        {
            System.err.println("Fatal protocol violation: " + e.getMessage());
            e.printStackTrace();
        } catch (IOException e)
        {
            System.err.println("Fatal transport error: " + e.getMessage());
            e.printStackTrace();
        } finally
        {
            // Release the connection.
            method.releaseConnection();
        }
        return responseBody;
    }

}
